﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

using mvcForum.Core;
using mvcForum.Web.Controllers;
using mvcForum.Web.ViewModels;
using mvcForum.Web.ViewModels.Create;
using mvcForum.Web.Areas.ForumAdmin.Helpers;
using mvcForum.Web.Interfaces;
using mvcForum.Core.Interfaces.Services;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Areas.ForumAdmin.Controllers {

	public class CategoryController : ForumAdminBaseController {
		private readonly IRepository<Board> boardRepo;
		private readonly IRepository<Category> categoryRepo;
		private readonly IMembershipService membershipService;

		public CategoryController(IWebUserProvider userProvider, IContext context, IMembershipService membershipService)
			: base(userProvider, context) {

			this.boardRepo = this.GetRepository<Board>();
			this.categoryRepo = this.GetRepository<Category>();
			this.membershipService = membershipService;
		}

		#region Create
		public ActionResult Create(int id) {
			Board board = this.boardRepo.Read(id);
			if (this.membershipService.IsAccountInRole(this.ActiveUser.EmailAddress, "Board")) {
				// TODO:
				//Boolean found = false;
				//var admins = this.adminRepo.ReadMany(new AdministrationSpecifications.SpecificUser(this.ActiveUser));
				//foreach (var admin in admins) {
				//    if (admin.Board.Id == id) {
				//        found = true;
				//    }
				//}
				//if (!found) {
				//    TempData.Add("Reason", String.Format("You are not allowed to create categories on board {0}", board.Name));
				//    return RedirectToAction("NoAccess", "Forum");
				//}
			}
			CreateCategoryViewModel category = new CreateCategoryViewModel { BoardId = board.Id };
			return View(category);
		}

		[HttpPost]
		public ActionResult Create(CreateCategoryViewModel model) {
			if (ModelState.IsValid) {
				Board board = this.boardRepo.Read(model.BoardId);
				if (this.membershipService.IsAccountInRole(this.ActiveUser.EmailAddress, "Board")) {
					// TODO:
					//Boolean found = false;
					//var admins = this.adminRepo.ReadMany(new AdministrationSpecifications.SpecificUser(this.ActiveUser));
					//foreach (var admin in admins) {
					//    if (admin.Board.Id == model.BoardId) {
					//        found = true;
					//    }
					//}
					//if (!found) {
					//    TempData.Add("Reason", String.Format("You are not allowed to create categories on board {0}", board.Name));
					//    return RedirectToAction("NoAccess", "Forum");
					//}
				}

				Category category = new Category(board, model.Name, model.SortOrder);
				this.categoryRepo.Create(category);
				this.Context.SaveChanges();

				return RedirectToAction("Edit", "Board", new RouteValueDictionary { { "id", board.Id } });
			}
			return View(model);
		}
		#endregion

		#region Update
		public ActionResult Update(Int32 id) {
			// TODO: Validate access!
			Category category = this.categoryRepo.Read(id);

			return View(new mvcForum.Web.Areas.ForumAdmin.ViewModels.Category { Id = id, Path = BreadcrumbHelper.BuildPath(category, Url) });
		}
		#endregion

		#region Delete
		public ActionResult Delete(Int32 id) {
			// TODO: Access!!
			var model = new CategoryViewModel(this.categoryRepo.Read(id));
			return View(model);
		}

		[HttpPost]
		public ActionResult Delete(Int32 id, Boolean confirm) {
			// TODO: Access!!
			Category category = this.categoryRepo.Read(id);
			if (ModelState.IsValid && confirm) {
				this.categoryRepo.Delete(category);
				this.Context.SaveChanges();

				if (Request.IsAjaxRequest()) {
					return Json(true);
				}

				return RedirectToAction("Edit", "Board", new RouteValueDictionary { { "id", category.Board.Id } });
			}

			if (Request.IsAjaxRequest()) {
				return Json(true);
			}

			var model = new CategoryViewModel(category);
			return View(model);
		}
		#endregion

		#region Private methods
		[NonAction]
		private void AddForums(Category category, CategoryViewModel model) {
			List<ForumViewModel> forumModels = new List<ForumViewModel>();
			foreach (var forum in category.Forums.OrderBy(x => x.SortOrder)) {
				forumModels.Add(new ForumViewModel(forum, 0, Core.Configuration.AdminAuthorNameSetting.Username));
			}
			model.Forums = new ReadOnlyCollection<ForumViewModel>(forumModels);
		}
		#endregion
	}
}